type StorageValue = string | number | boolean | object | null;

class LocalStore {
  private prefix: string;

  constructor(prefix = 'app_') {
    this.prefix = prefix;
  }

  private getKey(key: string) {
    return `${this.prefix}${key}`;
  }

  /**
   * 设置本地存储
   * @param key 键名
   * @param value 值，可以是对象、数组、基本类型
   */
  set<T extends StorageValue>(key: string, value: T): void {
    try {
      const stringValue = typeof value === 'string' ? value : JSON.stringify(value);
      localStorage.setItem(this.getKey(key), stringValue);
    } catch (error) {
      console.error('LocalStore set error:', error);
    }
  }

  /**
   * 获取本地存储
   * @param key 键名
   * @param defaultValue 默认值
   */
  get<T extends StorageValue>(key: string, defaultValue: T | null = null): T | null {
    try {
      const value = localStorage.getItem(this.getKey(key));
      if (value === null) return defaultValue;

      // 尝试解析 JSON
      try {
        return JSON.parse(value) as T;
      } catch {
        return value as unknown as T;
      }
    } catch (error) {
      console.error('LocalStore get error:', error);
      return defaultValue;
    }
  }

  /**
   * 删除本地存储
   */
  remove(key: string): void {
    try {
      localStorage.removeItem(this.getKey(key));
    } catch (error) {
      console.error('LocalStore remove error:', error);
    }
  }

  /**
   * 清空本地存储（仅清空当前前缀）
   */
  clear(): void {
    try {
      const keysToRemove: string[] = [];
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);
        if (key && key.startsWith(this.prefix)) keysToRemove.push(key);
      }
      keysToRemove.forEach((key) => localStorage.removeItem(key));
    } catch (error) {
      console.error('LocalStore clear error:', error);
    }
  }
}

// 默认导出一个实例
export default new LocalStore();
